#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/10 11:58
    Desc  :
--------------------------------------
"""
import json

from flask import Blueprint, render_template, request
from application import app
from common.libs.JsonResponseUtils import JsonResponse
from common.libs.JwtUtils import verify_jwt
from common.libs.PhoneCheckUtils import PhoneCheckUtils
from common.libs.QuerySetUtils import QuerySetUtils
from common.libs.paginationUtils import PaginationUtils, ListPaginationUtils
from common.libs.queryListUtils import QueryListUtils
from servers.models.userModel import User

user_route = Blueprint('user', __name__)
ADMIN = 100


# 用户列表
@user_route.route('/list', methods=["POST"])
def userList():
    try:
        form = {} if not request.json else dict(request.json)
        page, size = form.get('page'), form.get('size')
        form = QueryListUtils(form).filter_by('icontains')
        user = User.objects(
            admin=ADMIN, **form).exclude('password').order_by('-id')
        pagination = ListPaginationUtils(user, **form)
        return JsonResponse(code=20000, data=pagination.items, message='请求成功').jsonExit()

    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 新增用户
@user_route.route('/add', methods=["POST"])
def userAdd():
    try:
        form = {} if not request.json else dict(request.json)
        form = QuerySetUtils(User).filterField(form)

        if form.get("username") is None or form.get("username") == "":
            return JsonResponse(code=40002, data=None, message="username不能为空").jsonExit()
        if form.get('phone') is None or form.get("phone") == '':
            return JsonResponse(code=40002, data=None, message="phone不能为空").jsonExit()
        if not PhoneCheckUtils(form.get('phone')).phone_check():
            return JsonResponse(code=40006, data=None, message="phone格式错误").jsonExit()
        if User.objects(username=form.get("username"), admin=ADMIN).count() != 0:
            return JsonResponse(code=40003, data=None, message="username已存在").jsonExit()
        if User.objects(username=form.get("phone"), admin=ADMIN).count() != 0:
            return JsonResponse(code=40003, data=None, message="phone已被使用").jsonExit()
        # add_valid_user(ADMIN, **form)
        form['admin'] = ADMIN
        user = User(**form)
        user.save()
        return JsonResponse(code=20000, data=user.to_json(), message="请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 用户详情
@user_route.route('/info', methods=['POST'])
def userInfo():
    try:
        accesstoken = request.headers.get('accesstoken')
        if verify_jwt(accesstoken) is None:
            return JsonResponse(code=40004, data=None, message="accesstoken失效").jsonExit()
        username = verify_jwt(accesstoken).get('username')
        print(verify_jwt(accesstoken))
        # if form.get("id") is None or form.get("id") == "":
        #     return JsonResponse(code = 40002, data = None, message = "id不能为空").jsonExit()

        user = User.objects(username=username, admin=ADMIN)

        return JsonResponse(code=20000, data=user.first().to_json(), message="请求成功").jsonExit()

    except Exception as e:
        app.logger.error(Exception(e))
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 用户编辑
@user_route.route('/edit', methods=['POST'])
def userEdit():
    try:
        form = {} if not request.json else dict(request.json)
        form = QuerySetUtils(User).filterField(form)

        if form.get("id") is None or form.get("id") == "":
            return JsonResponse(code=40002, data=None, message="id不能为空").jsonExit()
        user = User.objects(id=form.get('id'), admin=ADMIN)
        if user.count() == 0:
            return JsonResponse(code=40005, data=None, message="用户不存在").jsonExit()
        user.update(**form)
        return JsonResponse(code=20000, data=user.exclude('password'), message="请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 用户删除
@user_route.route('/delete', methods=['POST'])
def userDelete():
    try:
        form = {} if not request.json else dict(request.json)
        if form.get("id") is None or form.get("id") == "":
            return JsonResponse(code=40002, data=None, message="id不能为空").jsonExit()
        user = User.objects(id=form.get('id'), admin=ADMIN)
        if user.count() == 0:
            return JsonResponse(code=40005, data=None, message="用户不存在").jsonExit()
        user.delete()
        return JsonResponse(code=20000, data=None, message="请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 用户登录
@user_route.route('/login', methods=['POST'])
def userLogin():
    try:

        form = {} if not request.json else dict(request.json)
        username, password = form.get('username'), form.get('password')
        user_name = User.objects(username=username, admin=ADMIN)
        user_phone = User.objects(phone=username, admin=ADMIN)

        if username is None or username == '':
            return JsonResponse(code=40002, data=None, message="username不能为空").jsonExit()
        if password is None or password == '':
            return JsonResponse(code=40002, data=None, message="password不能为空").jsonExit()

        if user_name.count() == 0 and user_phone.count() == 0:
            return JsonResponse(code=40003, data=None, message="用户不存在").jsonExit()
        if user_name.count() == 0:
            user = user_phone
        else:
            user = user_name
        if user.first().password != password:
            return JsonResponse(code=40004, data=None, message="密码错误").jsonExit()

        return JsonResponse(code=20000, data=user.first().login_to_json(), message="请求成功").jsonExit()

    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 用户退出登录
@user_route.route('/logout', methods=['POST'])
def userLogout():
    try:
        return JsonResponse(code=20000, data=None, message="请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()
